import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by Administrator on 2015/12/30.
 */
public class ExplicitCriticalSection {
    public static void main(String[] args) {
        PairManager pman1 = new ExplicitPairManager1();
        PairManager pman2 = new ExplicitPairManager2();
        CriticalSection.testApproaches(pman1,pman2);
    }
}

class ExplicitPairManager1 extends PairManager{
    private Lock lock = new ReentrantLock();

    @Override
    public synchronized void increment() {
        lock.lock();
        try {
            p.incrementX();
            p.incrementY();
            try {
                TimeUnit.MILLISECONDS.sleep(1000);//确保有足够时间持有getPair()锁
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            store(getPair());
        }finally {
            lock.unlock();
        }
    }
}

//使用临界区，但是线程不安全
class ExplicitPairManager2 extends  PairManager{
    private Lock lock = new ReentrantLock();

    @Override
    public void increment() {
        Pair temp;
        lock.lock();
        try {
            p.incrementX();
            p.incrementY();
            temp = getPair();
        } finally {
            lock.unlock();
        }
       store(temp);
    }
}